package com.unlcn.ils.wms.web.utils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;

/**
 *
 * Created by DELL on 2017/8/15.
 */
public class Vo2Bo<BO,VO> {
    private Logger LOGGER = LoggerFactory.getLogger(Vo2Bo.class);
    /**
     * 单个对象转换
     */
    public BO convert(VO from, Class<BO> clazz) {
        if (from == null) {
            return null;
        }
        BO to = null;
        try {
            to = clazz.newInstance();
        } catch (Exception e) {
            LOGGER.error("初始化{}对象失败。", clazz, e);
        }
        convert(from, to);
        return to;
    }

    /**
     * 批量对象转换
     */
    public List<BO> convert(List<VO> fromList, Class<BO> clazz) {
        if (CollectionUtils.isEmpty(fromList)) {
            return null;
        }
        List<BO> toList = new ArrayList<BO>();
        for (VO from : fromList) {
            toList.add(convert(from, clazz));
        }
        return toList;
    }

    /**
     * 属性拷贝方法，有特殊需求时子类覆写此方法
     */
    protected void convert(VO from, BO to) {
        BeanUtils.copyProperties(from, to);
    }
}
